package com.dbq.fast.business.coupons;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.coupons.bean.ContentBean;
import com.dbq.fast.business.coupons.bean.CouponsData;
import com.dbq.fast.business.coupons.bean.Page;
import com.dbq.fast.business.login.api.LoginApi;
import com.dbq.fast.business.product.api.CommonTransformer;
import com.dbq.fast.business.product.bean.ProductType;
import com.dbq.fast.business.product.ui.StatusView;
import com.dbq.fast.common.base.BaseActivity;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.net.HttpManager;
import com.dbq.fast.common.net.RemoteApiCallBack;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 *TODO  该界面未做分页加载的处理
 * TODO  将字符串移到string.xml文件中
 */
public class ChooseCouponsActivity extends BaseActivity {
    private List<ContentBean>  data;
    private ArrayList<ContentBean> al0 = new ArrayList<>();
    private ArrayList<ContentBean> al2 = new ArrayList<>();

    private CouponsAdapter adapter;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.status_view)
    StatusView statusView;

    private ProductType.SetMealListBean psml;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_coupons);
        ButterKnife.bind(this);

        Serializable  sb = getIntent().getSerializableExtra("param");
        if (sb instanceof ProductType.SetMealListBean){
            psml = (ProductType.SetMealListBean) sb;
        }

        data = new ArrayList<>();
        adapter = new CouponsAdapter(this,data,al0,al2);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        statusView.setStatus(StatusView.LOADING);
        loadData(0);

        swipeRefreshLayout.setOnRefreshListener(() -> {
            loadData(0);
        });
        statusView.setRefreshListener(()->{
            loadData(0);
        });
        findViewById(R.id.back).setOnClickListener(v->finish());
    }
    private void loadData(int pageId){
        Page pageInfo = new Page();
        pageInfo.page = pageId;
        HttpManager.getInstance().getHttpService()//
                .getCoupons(User.getInstance().getToken(),pageInfo)//
                .compose(new CommonTransformer<>())//
                .subscribe(httpResult -> {
                    if (swipeRefreshLayout!=null&& swipeRefreshLayout.isRefreshing()){
                        swipeRefreshLayout.setRefreshing(false);
                    }
                    if (httpResult.getCode() == 200){
                        businessLogic(httpResult.getData());
                    }else if (httpResult.getCode() == 401){
                        refreshToken(pageId);
                    }}, throwable -> {
                    if (swipeRefreshLayout!=null&& swipeRefreshLayout.isRefreshing()){
                        swipeRefreshLayout.setRefreshing(false);
                    }
                    if (data.isEmpty()){
                        statusView.setStatus(StatusView.SERVICE_ERROR);
                    }else{
                        Toast.makeText(this,R.string.tip_retry_network_bad,Toast.LENGTH_SHORT).show();
                    }

                });
    }
    private void refreshToken(int pageId){
        LoginApi.refreshToken(true, new RemoteApiCallBack<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                loadData(pageId);
            }

            @Override
            public void onFail(int status, String message) {

            }
        });
    }

    private void businessLogic(CouponsData t) {
            data.clear();
            al0.clear();
            al2.clear();
        Log.i("content",t.userDiscountPage.content.toString());
        for (ContentBean item : t.userDiscountPage.content){
            if (item.discountStatus == 0){ //卡券未使用
                //可使用的卡券需要通过月份和时间一起判断
                if (item.discount.discountSetmealTime == psml.setMealTime){ //判断月份是否满足使用条件
                    if (item.timeRemain <= 0){ // 判断使用时间是否已经过期
                        item.viewType = 4;
                        al2.add(item);
                    }else{ //月份满足条件同时还在使用范围类的卡券
                        item.viewType = 2;
                        al0.add(item);
                    }
                }else{ //不符合月份使用条件的，直接放入不可使用的卡券结合中
                    item.viewType = 4;
                    al2.add(item);
                }
            }
        }
        if (!t.userDiscountPage.content.isEmpty()){ //当返回的数据不为空的时候，才处理数据
            //添加标题数据
            ContentBean cb0 = new ContentBean();
            cb0.viewType = 1;
            data.add(cb0);

            if (al0.isEmpty()){ //添加数据为空的时候，默认数据
                cb0 = new ContentBean();
                cb0.viewType = 0;
                data.add(cb0);
            }else{
                data.addAll(al0);
            }

            if (!al2.isEmpty()){
                //添加标题数据
                cb0 = new ContentBean();
                cb0.viewType = 3;
                data.add(cb0);
                data.addAll(al2);
            }
        }
        statusView.setStatus(data.isEmpty() ? StatusView.NO_COUPONS:StatusView.SUCCESS);
        adapter.notifyDataSetChanged();
    }
    private class CouponsAdapter extends RecyclerView.Adapter{

        private List<ContentBean> list;
        private LayoutInflater inflater;

        public CouponsAdapter(Context context, List<ContentBean> list,List<ContentBean> valid,List<ContentBean> unValid){
            this.list = list;
            inflater = LayoutInflater.from(context);
        }


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == 2 || viewType == 4){
                View rootView = inflater.inflate(R.layout.adapter_coupons_item_view,null);
                return new CouponsHolder(rootView);
            }else if (viewType == 0 ){
                View rootView = inflater.inflate(R.layout.adapter_coupons_data_empty,null);
                return new DataEmptyHolder(rootView);
            }else if (viewType == 1 ){
                View rootView = inflater.inflate(R.layout.adapter_coupons_title_view,null);
                return new TitleHolder(rootView);
            }else if (viewType == 3 ){
                View rootView = inflater.inflate(R.layout.adapter_coupons_title_view,null);
                return new TitleHolder(rootView);
            }
            return null;
        }

        @Override
        public int getItemViewType(int position) {
            return list.get(position).viewType;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            int viewType = getItemViewType(position);
            Resources resources = holder.itemView.getContext().getResources();
            if(holder instanceof CouponsHolder){

                if (getItemViewType(position) == 2 || getItemViewType(position) == 4){ //类型为有效数据时，展示不同的数据
                    CouponsHolder h = (CouponsHolder) holder;
                    ContentBean cb =  data.get(position);
                    h.discountAmout.setText(cb.discount.discountAmount+"折");
                    h.couponsTitle.setText(cb.discount.discountName);
                    h.discountExpire.setText(String.format("限%s个月套餐使用",getChinesChar(cb.discount.discountSetmealTime)));
                    h.validTime.setText(String.format("有效期至%s",getValidTime(cb.discountExpired)));
                    h.leftTime.setText(getLeftTime(cb.timeRemain));
                    if ( viewType== 2){//第一页有不同的颜色
                        h.discountAmout.setTextColor(resources.getColor(R.color.coupons_color));
                        h.couponsTitle.setTextColor(resources.getColor(R.color.coupons_black));
                        h.discountExpire.setTextColor(resources.getColor(R.color.font_normal));
                        h.validTime.setTextColor(resources.getColor(R.color.font_normal));
                        h.leftTime.setTextColor(resources.getColor(R.color.coupons_color));
                    }else if(viewType == 4){ //未使用和已过期的界面都显示为灰色
                        h.discountAmout.setTextColor(resources.getColor(R.color.font_normal));
                        h.couponsTitle.setTextColor(resources.getColor(R.color.font_normal));
                        h.discountExpire.setTextColor(resources.getColor(R.color.font_normal));
                        h.validTime.setTextColor(resources.getColor(R.color.font_normal));
                        h.leftTime.setTextColor(resources.getColor(R.color.font_normal));
                    }
                    if (viewType == 2){
                        holder.itemView.setOnClickListener(v -> {
                            Intent  intent = new Intent();
                            intent.putExtra("result",cb);
                            YibaAnalysis.getInstance().event(ChooseCouponsActivity.this, EventConstant.EVENT_CLICK_COUPON_X+cb.discount.discountAmount);
                            setResult(RESULT_OK,intent);
                            finish();
                        });
                    }
                }

            }else if (holder instanceof TitleHolder){
                TitleHolder h = (TitleHolder) holder;
                h.typeTitle.setText(viewType == 1 ?""/*resources.getString(R.string.valid_coupons)*/:""/*resources.getString(R.string.unValid_coupons)*/);
            }
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        private String getValidTime(long discountExpired){
            Date d = new Date(discountExpired);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.format(d);
        }
        private String getLeftTime(long timeRemain){
            if (timeRemain <= 0){
                return "已过期";
            }else if (timeRemain < 24 * 60 * 60 * 1000){
                return "不足一天";
            }else if (timeRemain < 24 * 60 * 60 * 1000 * 2){
                return "不足二天";
            }else if (timeRemain < 24 * 60 * 60 * 1000 * 3){
                return "不足三天";
            }else if (timeRemain < 24 * 60 * 60 * 1000 * 4){
                return "不足四天";
            }
            return "";
        }
        /**
         * 将返回的月份转换为中文
         * @param mouth
         * @return
         */
        private String getChinesChar(int mouth){
            String t = "一";
            if (mouth == 1){
                t = "一";
            }else if(mouth == 3){
                t = "三";
            }else if(mouth == 6){
                t = "六";
            }else if(mouth == 12){
                t = "十二";
            }
            return t;
        }
    }


    public class CouponsHolder extends RecyclerView.ViewHolder{
        @BindView(R.id.discount_amount)
        TextView discountAmout;

        @BindView(R.id.coupons_title)
        TextView couponsTitle;

        @BindView(R.id.discount_expire)
        TextView discountExpire;

        @BindView(R.id.valid_time)
        TextView validTime;

        @BindView(R.id.left_time)
        TextView leftTime;//剩余时间
        public CouponsHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }
    public class TitleHolder extends RecyclerView.ViewHolder{
        @BindView(R.id.coupons_type_title)
        TextView typeTitle;

        public TitleHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }
    public class DataEmptyHolder extends RecyclerView.ViewHolder{

        public DataEmptyHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }

}
